package  
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.events.KeyboardEvent;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.text.TextLineMetrics;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	/**
	 * ...
	 * @author Sang Tian
	 */
	public class Terminal extends Sprite
	{
		private var _buffer:StringBuilder;
		private var _textBuffer:TextField;
		private var _displayBuffer:BitmapData;
		//private var _cursorCol:uint = 0;
		//private var _cursorRow:uint = 0;
		
		public var cmd:CommandLine;
		private var _currentCmd:CommandLine;
		
		public function Terminal(width:uint, height:uint) 
		{
			_buffer = new StringBuilder();
			_textBuffer = new TextField();
			_textBuffer.width = width;
			_textBuffer.height = height;
			_textBuffer.wordWrap = true;
			_textBuffer.textColor = 0xffffff;
			
			_displayBuffer = new BitmapData(width, height, false);
			var bmp:Bitmap = new Bitmap(_displayBuffer);
			addChild(bmp);
			
			cmd = new CommandLine();
			_currentCmd = cmd;
		}
		
		public function input(e:KeyboardEvent):void 
		{
			if (e.ctrlKey)
			{
				if (e.altKey == false)
				{
					if (e.charCode)
					{
						processCommand(e.charCode);
					}
				}
				return;
			}
			
			if (e.charCode == 0)
				return;
			if (e.keyCode == Keyboard.BACKSPACE)
			{
				_buffer.backspace();
				//_cursorCol--;
				return;
			}
			//_cursorCol++;
			_buffer.appendChar(e.charCode);
			_textBuffer.text = _buffer.toString();
			if (_textBuffer.maxScrollH
		}
		
		private function processCommand(charCode:uint):void 
		{
			var s:String = String.fromCharCode(charCode);
			if (s == 'g')
				_buffer.appendString("hello:");
		}
		
		public function refresh(time:uint):void
		{
			_currentCmd.refresh(time);
			_displayBuffer.fillRect(_displayBuffer.rect, 0x000000);
			_displayBuffer.draw(_textBuffer);
			updateCursor();
		}
		
		public function get textFormat():TextFormat
		{
			return _textBuffer.defaultTextFormat;
		}
		
		public function setTextFormat(props:Object):void
		{
			var format:TextFormat = _textBuffer.defaultTextFormat;
			for (var key:String in props)
			{
				format[key] = props[key];
			}
			_textBuffer.defaultTextFormat = format;
		}
		
		private function updateCursor():void 
		{
			var line:int = _textBuffer.numLines - 1;
			var tm:TextLineMetrics = _textBuffer.getLineMetrics(line);
			var cx:int = textFormat.leftMargin + tm.width;
			var cy:int = (line + 1) * tm.height;
			_displayBuffer.fillRect(new Rectangle(cx + 2, cy, 10, 2), 0xffffff);
		}
	}

}